<template>
	<view>

		<z-paging ref="paging" v-model="dataList" @query="queryList" :refresher-enabled="false">
			<template #top>
				<tn-navbar fixed home-icon="" bg-color="#00aaff">
					<text class="tn-white_text">车场详情</text>

				</tn-navbar>
			</template>
			<view class="bg-card  ">
				<TabControl :tabs="tabs" :currentTab="currentTab" :changeTab="changeTab" />
				<view v-if="currentTab === 0" class="tab1">
					<Card :billsType="billsType" :carPark="carPark" @change="changeBillsType" @confirmDate="confirmDate" @flushData="queryDatas" :dateStr="dateStr" />
					<box title="收入对比">
					  <qiun-data-charts canvas2d  type="column" :opts="charOption" :chartData="charData"     />
					</box> 
				 
					<IncomeStatistics :dataList="dailyIncomeStatisticsList" :currentCollapse="billsDetailIndex"
						@change="handleBillsDetailChange" />
				</view>
				<view v-if="currentTab === 1" class="tab2">
					<DeviceCard :title="carPark.name" keyName="id" :dataList="dataList" @open="handleOpen"
						@close="handleClose" @view="handleView"  />
				</view>
				<view v-if="currentTab === 2" class="tab3">
					<GridList :dataList="menusData" :carPark="carPark" /> <!-- 使用 GridList 组件 -->
				</view>
				<view class="tn-tabbar-height"></view>
			</view>
			<template #loadingMoreNoMore>
				<view></view>
			</template>
		</z-paging>
		
	</view>
	
</template>
<script lang="ts">
export default {
	options: {
		styleIsolation: 'shared'
	}
}
</script>
<script setup lang="ts">
import box from '@/components/global-box/index.vue';
import TabControl from './components/detail/TabControl.vue';
import Card from './components/detail/Card.vue';
import IncomeStatistics from './components/detail/IncomeStatistics.vue' 
import DeviceCard from './components/detail/DeviceCard.vue'
import GridList from './components/detail/GridList.vue'
import { onShow, onLoad} from "@dcloudio/uni-app";
import { ref, onMounted } from "vue";
import { toast } from "@/utils/message";
import { tnParamById } from "@/utils/tnUtil";
 
import { menusData, monthOpts} from '@/utils/mock'
import CfIOTUtil from "@/cfsheep/api/iot/iot";
import CfPayUtil from "@/cfsheep/api/pay/pay";
import dayjs from "dayjs";
import CfCarParkUtil from "@/cfsheep/api/cfCarPark/park";

const tabs = ["收费统计", "设备监控", "功能列表"]; // 更新标签
const currentTab = ref(1); // 默认选中第二个标签


// 模拟图表数据
const charOption = ref({});
// 模拟图表数据
const charData = ref({
  categories: [
  ],
  series: [{
    name: "收入",
    data: [300, 1340, 2578, 3700, 6688, 8980, 5800, 4677, 3700],
    legendShape: "circle",
    color: "#4B98FE",
  },
    {
      name: "支出",
      data: [332, 1193, 1162, 1157, 1189, 2432, 1643, 1321, 1238],
      legendShape: "circle",
      color: "#FFAC00",
    },
  ]
});
//停车场
const dailyIncomeStatisticsList = ref([
  {
    name: "临停收入",
    money: "0",
    icon: 'lucky-money',
    color: 'tn-blue-dark',
    type: "1",
    children: [

    ],
  },
  {
    name: "套餐收入",
    money: "0",
    icon: 'payment-wechat',
    color: 'tn-teal-dark',
    type: "1",
    children: [

    ],
  },
  {
    name: "储值卡收入",
    money: "0",
    icon: 'payment-wechat',
    color: 'tn-teal-dark',

    type: "1",
    children: [

    ],
  },
  {
    name: "总停车次数",
    type: "2",
    num: "0",
    icon: 'fish',
    color: 'tn-orange',
  },
  {
    name: "总临时车停车次数",
    type: "2",
    num: "0",
    icon: 'fish',
    color: 'tn-orange',
  },
  {
    name: "总车位数",
    type: "2",
    num: "0",
    icon: 'windmill',
    color: 'tn-teal-dark',
  },
  {
    name: "路边总车位数",
    type: "2",
    num: "0",
    icon: 'windmill',
    color: 'tn-teal-dark',
  },
  {
    name: "总已使用车位数",
    type: "2",
    num: "0",
    icon: 'windmill',
    color: 'tn-teal-dark',
  },
  {
    name: "路边已使用车位数",
    type: "2",
    num: "0",
    icon: 'windmill',
    color: 'tn-teal-dark',
  },
  {
    name: "无入场时间数",
    type: "2",
    num: "0",
    icon: 'windmill',
    color: 'tn-teal-dark',
  },
  {
    name: "异常放行数",
    type: "2",
    num: "0",
    icon: 'windmill',
    color: 'tn-teal-dark',
  },
  {
    name: "停车套餐数",
    type: "2",
    num: "0",
    icon: 'windmill',
    color: 'tn-teal-dark',
  },
  {
    name: "总停车时间(小时)",
    type: "2",
    num: "0",
    icon: 'windmill',
    color: 'tn-teal-dark',
  },
  {
    name: "黄牌车数量",
    type: "2",
    num: "0",
    icon: 'windmill',
    color: 'tn-teal-dark',
  },
  {
    name: "蓝车牌数量",
    type: "2",
    num: "0",
    icon: 'windmill',
    color: 'tn-teal-dark',
  },
  {
    name: "绿车牌数量",
    type: "2",
    num: "0",
    icon: 'windmill',
    color: 'tn-teal-dark',
  },
  {
    name: "逃费次数",
    type: "2",
    num: "0",
    icon: 'windmill',
    color: 'tn-teal-dark',
  },
  {
    name: "追缴次数",
    type: "2",
    num: "0",
    icon: 'windmill',
    color: 'tn-teal-dark',
  }
]);
const carPark = ref({
  id: 0,
  name: '',
  dailyIncomeStatistics:
  {
    amountActuallyPaid: 0,
    amountsPayable: 0,
    countsTime: 0,
    date: 0,
    endTime: 0,
    goodsType: 0,
    id: 0,
    month: 10,
    payCounts: 0,
    paymentAgencyShortName: "",
    refundAmount: 0,
    shopId: 0,
    shopName: "",
    startTime: 0,
    title: "",
    year: 0
  },
  dailyIncomeStatisticsDayList:[
    {
      amountActuallyPaid: 0,
      amountsPayable: 0,
      countsTime: 0,
      date: 0,
      endTime: 0,
      goodsType: 0,
      id: 0,
      month: 10,
      payCounts: 0,
      paymentAgencyShortName: "",
      refundAmount: 0,
      shopId: 0,
      shopName: "",
      startTime: 0,
      title: "",
      year: 0
    }
  ],
  dailyIncomeStatisticsMonthList:[
    {
      amountActuallyPaid: 0,
      amountsPayable: 0,
      countsTime: 0,
      date: 0,
      endTime: 0,
      goodsType: 0,
      id: 0,
      month: 10,
      payCounts: 0,
      paymentAgencyShortName: "",
      refundAmount: 0,
      shopId: 0,
      shopName: "",
      startTime: 0,
      title: "",
      year: 0
    }
  ],
  dateData: {
    year: 0,
    month: 0,
    day: 0,
    minStartTime: 0,
    maxEndTime: 0
  }
});

const getCharData = () => { 
	// 获取模拟图表数据
	charOption.value = monthOpts;
}




// 账单类型
const billsType = ref(0);
// 收入统计 索引 
const changeBillsType = (index: number) => {
	billsType.value = index; // 更新账单类型
  queryDatas();
};

const billsDetailIndex = ref<Number>()
const handleBillsDetailChange = (value: any) => {
	billsDetailIndex.value = value;
}
// 统计数据
const billsDetailList = ref([]);
// ============== tab2   设备监控 =====================================
// 开闸事件
const handleOpen = async (_deviceId: number) => {
  _controllerDeviceSwitch(_deviceId, 'on');
}
// 落闸事件
const handleClose = (_deviceId: number) => {
  _controllerDeviceSwitch(_deviceId, 'off');
}

/**
 * 控制开关闸
 * @param _deviceId
 */
const _controllerDeviceSwitch = async (_deviceId: number, _action: string) => {
  const controllerResult = await CfIOTUtil.controllerDeviceSwitch({
    action: _action,
    deviceId: _deviceId
  });
  if(controllerResult.code == 10002){
    toast('操作设备-成功');
  }else{
    toast('操作设备-失败-' + controllerResult.message + '-' + controllerResult.mixMessage);
  }
}



// 通道事件
const handleView = (value: any) => {
	tnParamById('/pages/main/parkingLot/warning', JSON.stringify(value))
}
const deviceList = ref([]);

// z-paging 示例
const paging = ref(null);
// 数据列表
const dataList = ref();

/**
 * 该区对应停车场的设备
 * @param pageNo
 * @param pageSize
 */
const queryList = async (pageNo: number, pageSize: number) => {
  const _deviceList = await CfIOTUtil.getDeviceListByQuery({
    page: pageNo,
    size: pageSize,
    areaId: carPark.value.id,
    deviceType: 2
  });
  if(_deviceList.code == 10002){
    deviceList.value = _deviceList.data;
  }else{
    deviceList.value = [];
  }
  paging.value.complete(deviceList.value);
};

//获取财务报表
const getDailyIncomeStatisticsList = async (_shopId: number, _year: number, _month: number, _date: number, _goodsType: number, _statisticalModel: string, _orderByAsc: string, _orderByDesc: string, _paymentAgencyShortName: string, _minStartTime: number, _maxEndTime: number) => {
  let params = {
    page: 1,
    size: 20,
    shopId: _shopId,
    year: _year,
    month: _month,
    date: _date,
    orderByAsc: _orderByAsc,
    orderByDesc: _orderByDesc,
    goodsType: _goodsType,
    statisticalModel: _statisticalModel,
    paymentAgencyShortName: _paymentAgencyShortName,
    minStartTime: _minStartTime,
    maxEndTime: _maxEndTime,
  }
  if(_shopId===null){
    delete params.shopId;
  }
  if(_paymentAgencyShortName===null){
    delete params.paymentAgencyShortName;
  }
  if(_year===null){
    delete params.year;
  }
  if(_month===null){
    delete params.month;
  }
  if(_date===null){
    delete params.date;
  }
  if(_minStartTime===null){
    delete params.minStartTime;
  }
  if(_maxEndTime===null){
    delete params.maxEndTime;
  }
  if(_orderByAsc===null){
    delete params.orderByAsc;
  }
  if(_orderByDesc===null){
    delete params.orderByDesc;
  }
  const _dailyIncomeStatisticsList = await CfPayUtil.getDailyIncomeStatisticsListByQuery(params);
  if(_dailyIncomeStatisticsList.code == 10002){
    return _dailyIncomeStatisticsList.data;
  }else{
    return [];
  }
}

//获取停车数据报表
const getDailyParkingStatistcsList = async (_year: number, _month: number, _date: number) => {
  const _dailyParkingStatistcsList = await CfCarParkUtil.getDailyParkingStatistcsListByQuery({
    page: 1,
    size: 20,
    carParkId: carPark.value.id,
    year: _year,
    month: _month,
    date: _date,
  });
  if(_dailyParkingStatistcsList.code == 10002){
    return _dailyParkingStatistcsList.data;
  }else{
    return [];
  }
}


const changeTab = (index: number) => {
	currentTab.value = index;
};

/**
 * 执行数据查询
 */
const queryDatas = () => {
  //总收入
  getDailyIncomeStatisticsList(carPark.value.id, carPark.value.dateData.year, carPark.value.dateData.month, carPark.value.dateData.day, 0, 'statistical_model_sum_day', '', '', '', null, null).then((data)=>{
    carPark.value.dailyIncomeStatistics = data[0];
  });
  //临停收入
  getDailyIncomeStatisticsList(carPark.value.id, carPark.value.dateData.year, carPark.value.dateData.month, carPark.value.dateData.day, 1, '', '', 'counts_time', null, null, null).then((data)=>{
    if(data.length>0){
      dailyIncomeStatisticsList.value[0].money = data[0].amountActuallyPaid;
      dailyIncomeStatisticsList.value[0].children = [];
      for(let i=1; i<data.length; i++){
        dailyIncomeStatisticsList.value[0].children.push(data[i]);
      }
    }
  });
  //套餐收入
  getDailyIncomeStatisticsList(carPark.value.id, carPark.value.dateData.year, carPark.value.dateData.month, carPark.value.dateData.day, 5, '', '', 'counts_time', null, null, null).then((data)=>{
    if(data.length>0){
      dailyIncomeStatisticsList.value[1].money = data[0].amountActuallyPaid;
      dailyIncomeStatisticsList.value[1].children = [];
      for(let i=1; i<data.length; i++){
        dailyIncomeStatisticsList.value[1].children.push(data[i]);
      }
    }
  });
  //储值卡收入
  getDailyIncomeStatisticsList(carPark.value.id, carPark.value.dateData.year, carPark.value.dateData.month, carPark.value.dateData.day, 14, '', '', 'counts_time', null, null, null).then((data)=>{
    if(data.length>0){
      dailyIncomeStatisticsList.value[2].money = data[0].amountActuallyPaid;
      dailyIncomeStatisticsList.value[2].children = [];
      for(let i=1; i<data.length; i++){
        dailyIncomeStatisticsList.value[2].children.push(data[i]);
      }
    }
  });

  if(billsType.value==0){
    charData.value.categories = [];
    charData.value.series = [];
    //临停最近9天内的财务报表
    getDailyIncomeStatisticsList(carPark.value.id, null, null, null, 1, 'statistical_model_sum_day', 'counts_time', '', '', carPark.value.dateData.minStartTime, carPark.value.dateData.maxEndTime).then((data)=>{
      if(data.length>0){
        carPark.value.dailyIncomeStatisticsDayList = data;
        for(let i=8; i>=0; i--){
          charData.value.categories.push(dayjs().subtract(i, 'day').format('DD').valueOf());
        }
        charData.value.series[0] = {
          name: "临停",
          data: [],
          legendShape: "circle",
          color: "#4B98FE",
        };
        for(let i=0; i<data.length; i++){
          charData.value.series[0].data.push(data[i].amountActuallyPaid);
        }
      }
    });
    //停车套餐最近9天内的财务报表
    getDailyIncomeStatisticsList(carPark.value.id, null, null, null, 5, 'statistical_model_sum_day', 'counts_time', '', '', carPark.value.dateData.minStartTime, carPark.value.dateData.maxEndTime).then((data)=>{
      if(data.length>0){
        carPark.value.dailyIncomeStatisticsDayList = data;
        charData.value.series[1] = {
          name: "套餐",
          data: [],
          legendShape: "circle",
          color: "#FFAC00",
        };
        for(let i=0; i<data.length; i++){
          charData.value.series[1].data.push(data[i].amountActuallyPaid);
        }
      }
    });
  }else{
    charData.value.categories = [];
    charData.value.series = [];
    //临停最近9个月内的财务报表
    getDailyIncomeStatisticsList(carPark.value.id, null, null, 0, 1, 'statistical_model_sum_month', 'counts_time', '', '', dayjs().subtract(8, 'month').startOf('month').valueOf(), dayjs().valueOf()).then((data)=>{
      if(data.length>0){
        carPark.value.dailyIncomeStatisticsMonthList = data;
        for(let i=8; i>=0; i--){
          charData.value.categories.push(dayjs().subtract(i, 'month').format('MM').valueOf());
        }
        charData.value.series[0] = {
          name: "临停",
          data: [],
          legendShape: "circle",
          color: "#4B98FE",
        };
        for(let i=0; i<data.length; i++){
          charData.value.series[0].data.push(data[i].amountActuallyPaid);
        }
      }
    });
    //停车套餐最近9个月内的财务报表
    getDailyIncomeStatisticsList(carPark.value.id, null, null, 0, 5, 'statistical_model_sum_month', 'counts_time', '', '', dayjs().subtract(8, 'month').startOf('month').valueOf(), dayjs().valueOf()).then((data)=>{
      if(data.length>0){
        carPark.value.dailyIncomeStatisticsMonthList = data;
        charData.value.series[1] = {
          name: "套餐",
          data: [],
          legendShape: "circle",
          color: "#FFAC00",
        };
        for(let i=0; i<data.length; i++){
          charData.value.series[1].data.push(data[i].amountActuallyPaid);
        }
      }
    });
  }

  //总停车次数
  getDailyParkingStatistcsList(carPark.value.dateData.year, carPark.value.dateData.month, carPark.value.dateData.day).then((data)=>{
    if(data.length>0){
      dailyIncomeStatisticsList.value[3].num = data[0].parkingCounts;
      dailyIncomeStatisticsList.value[4].num = data[0].parkingTemporaryCounts;
      dailyIncomeStatisticsList.value[5].num = data[0].parkingSpace;
      dailyIncomeStatisticsList.value[6].num = data[0].streetParkingSpace;
      dailyIncomeStatisticsList.value[7].num = data[0].parkingUsedSpace;
      dailyIncomeStatisticsList.value[8].num = data[0].streetParkingUsedSpace;
      dailyIncomeStatisticsList.value[9].num = data[0].parkingNotInTimeCounts;
      dailyIncomeStatisticsList.value[10].num = data[0].parkingAbnormalReleaseCounts;
      dailyIncomeStatisticsList.value[11].num = data[0].parkingPackageRenewalCounts;
      dailyIncomeStatisticsList.value[12].num = data[0].parkingTimeCounts;
      dailyIncomeStatisticsList.value[13].num = data[0].yellowNumberPlateCounts;
      dailyIncomeStatisticsList.value[14].num = data[0].blueNumberPlateCounts;
      dailyIncomeStatisticsList.value[15].num = data[0].greenNumberPlateCounts;
      dailyIncomeStatisticsList.value[16].num = data[0].evasionFeesCounts;
      dailyIncomeStatisticsList.value[17].num = data[0].recoveryCounts;
    }
  })
};

onShow(() => {
	getCharData();
})
onLoad((_carPark: any)=>{
  carPark.value = _carPark;
  carPark.value.dateData = {
    year: dayjs().year().valueOf(),
    month: dayjs().month()+1,
    day: parseInt(dayjs().format("DD")),
    minStartTime: dayjs().subtract(8, 'day').startOf('day').valueOf(),
    maxEndTime: dayjs().valueOf(),
  }
  queryDatas();
});

//  统计卡片切换日期 
const showDate = ref(false);
 

const confirmDate = (dateStr: String)=>{
  let dateArr = dateStr.split('/');
	// 查询选择事件信息
	carPark.value.dateData.year = parseInt(dateArr[0]);
	carPark.value.dateData.month = parseInt(dateArr[1]);
	carPark.value.dateData.day = parseInt(dateArr[2]);
  queryDatas();
}
onMounted(() => {
	// 初始化数据列表
	if (currentTab == 1) {
		paging.value.reload(true);
	}
});
</script>

<style lang="scss" scoped>
.bg-card {
		background: linear-gradient(to bottom, #00aaff 15%, #d5efff);
	height: 28%;
	/* 高度设置为15% */
	border-radius: 0 0 10px 10px;
	/* 圆角 */
	box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
	/* 阴影 */
	position: absolute;
	/* 确保层级最低 */
	top: 0;
	left: 0;
	right: 0;
	z-index: 0;

}
.tn-tabbar-height {
		min-height: 80rpx;
		height: calc(80rpx + env(safe-area-inset-bottom) / 2);
		height: calc(80rpx + constant(safe-area-inset-bottom));
	} 
</style>
